//
//  LogisticsCompleteViewController.m
//  Commerce
//
//  Created by xiaofeifei on 15/2/9.
//  Copyright (c) 2015年 fei. All rights reserved.
//

#import "LogisticsCompleteViewController.h"
#import "AreaViewController.h"
#import "GTMBase64.h"
#import "MJPhotoBrowser.h"
#import "MJPhoto.h"

@interface LogisticsCompleteViewController ()<AreaDelegate>{
    NSMutableArray *_photosList;
    BOOL _isStarting;
    NSString *_specialLineAreaIDs;
    NSString *_startingAreaIDs;
}

@end

@implementation LogisticsCompleteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _photosList = [[NSMutableArray alloc] initWithCapacity:10];

    // Do any additional setup after loading the view from its nib.
}

#pragma mark -请求接口
- (void)sendImage{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    for (int i ; i < [_photosList count]; i++) {
        NSMutableDictionary *parameters = [GlobalData paramterDic];
        UIImage *img =_photosList[i];
        NSData *data = UIImageJPEGRepresentation(img, 1);
        NSString *imageStr = [GTMBase64 stringByEncodingData:data];
        [parameters addEntriesFromDictionary:@{@"byte_str":imageStr,
                                               @"img_type":@"user",
                                               }];
        
        [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@sys/upfile",URL_ROOT]
                                        params:parameters
                                   requestMode:DGHTTPMethodPOST
                                   loadingShow:YES
                                  didFinshLoad:^(id result) {
                                      [SVProgressHUD dismiss];
                                      
                                  }];
    }
}

- (void)getCompleteUserInfo{
    [SVProgressHUD showWithStatus:@"加载中" maskType:SVProgressHUDMaskTypeBlack];
    NSString *uid = [[GlobalData sharedGlobalData] userinfoDic][@"UserID"];
    NSMutableDictionary *parameters = [GlobalData paramterDic];
    [parameters addEntriesFromDictionary:@{@"userid":uid,
                                           @"company_name":_companyNameField.text,
                                           @"true_name":_nameTextField.text,
                                           @"address":_addressTextField.text,
                                           @"mobile":_phoneTextField.text,
                                           @"special_line":_specialLineAreaIDs,
                                           @"special_name":_specialLineTextField.text,
                                           @"company_tel":_compantyTelTextField.text,
                                           @"from_line":_startingAreaIDs,
                                           @"fromline_name":_startingTextField.text
                                           }];
    [[BaseNetwork alloc] initWithMethodUrl:[NSString stringWithFormat:@"%@user/userinfo",URL_ROOT]
                                    params:parameters
                               requestMode:DGHTTPMethodPOST
                               loadingShow:YES
                              didFinshLoad:^(id result) {
                                  [SVProgressHUD dismiss];
                                   if (result[@"result"]) {
                                       [SVProgressHUD showSuccessWithStatus:@"提交成功，等待管理员审核"];
                                       [self backBtnAct:nil];
                                   }else{
                                       [SVProgressHUD showInfoWithStatus:@"提交失败"];
                                   }
                                  
                              }];
}

#pragma mark -IBAction
- (IBAction)saveUserInfo:(id)sender{
    if ([[GlobalData sharedGlobalData] userinfoDic] == nil) {
        [SVProgressHUD showInfoWithStatus:@"请先登录"];
    }
    else if (_companyNameField.text.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请填写公司名"];
    }
    else if (_nameTextField.text.length == 0){
        [SVProgressHUD showInfoWithStatus:@"请填写姓名"];
    }
    else if (_phoneTextField.text.length == 0){
        [SVProgressHUD showInfoWithStatus:@"请填写电话号码"];
    }
    else if (_addressTextField.text.length == 0){
        [SVProgressHUD showInfoWithStatus:@"请填写联系地址"];
    }
    else if (_specialLineTextField.text.length == 0){
        [SVProgressHUD showInfoWithStatus:@"请填写专线路线"];
    }
    else if (_compantyTelTextField.text.length == 0){
        [SVProgressHUD showInfoWithStatus:@"请填写固定电话"];
    }
    else{
        [self sendImage];
        [self getCompleteUserInfo];
    }
}

- (IBAction)clearUserInfo:(id)sender{
    _companyNameField.text = nil;
    _nameTextField.text = nil;
    _phoneTextField.text = nil;
    _addressTextField.text = nil;
    _compantyTelTextField.text = nil;
    _specialLineTextField.text = nil;
}

- (IBAction)gotoSelectArea:(id)sender{
    if ([(UIButton *)sender tag] == 1) {
        _isStarting = YES;
    }else{
        _isStarting = NO;
    }
    AreaViewController *vc = [[AreaViewController alloc] initWithNibName:nil bundle:nil];
    vc.typeNum = 4;
    vc.delegate =self;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)showAreaData:(NSInteger)TypeNum andAreaList:(NSArray *)areaList{
    NSString *name = @"";
    NSString *areaId = @"";
    for (NSDictionary *dic in areaList) {
        name = [NSString stringWithFormat:@"%@,%@",name,dic[@"AreaName"]];
        areaId = [NSString stringWithFormat:@"%@,%@",areaId,dic[@"AreaID"]];
    }
    if (_isStarting) {
        _startingTextField.text = name;
        _startingAreaIDs = areaId;
    }else{
        _specialLineTextField.text = name;
        _specialLineAreaIDs = areaId;
    }
}

#pragma mark -点击图片
- (IBAction)headerBtnAct:(id)sender {
    UIActionSheet *sheet;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        sheet  = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择",@"取消", nil];
    }
    else {
        
        sheet = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"从相册选择",@"取消", nil];
    }
    
    [sheet showInView:self.view withCompletionHandler:^(NSInteger buttonIndex) {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            switch (buttonIndex) {
                case 0:
                    // 相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                    
                case 1:
                    // 相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                case 2:
                    // 取消
                    return;
            }
        }
        else {
            if (buttonIndex != 0) {
                
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        
        imagePickerController.delegate = self;
        
        imagePickerController.allowsEditing = NO;
        
        imagePickerController.sourceType = sourceType;
        
        [(UINavigationController *)self.view.window.rootViewController presentViewController:imagePickerController animated:YES completion:^{}];
        
    }];
    
    
    [sheet showInView:[(UINavigationController *)self.view.window.rootViewController view]];
}

#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    image = [self useImage:image];
    
    [_photosList addObject:image];
    [self paretoImgs];
    //    _headData = [UIImageJPEGRepresentation(image, 0.5) retain];
    //    _headImg.image = image;
}

- (UIImage *)useImage:(UIImage *)image {
    //    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    // Create a graphics image context
    CGSize newSize = CGSizeMake(200, 200);
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    
    //    [pool release];
    return newImage;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
}


- (void)paretoImgs{
    //拍照
    float width = 35;
    float height = 35;
    float origX = 0;
    float origY = (_ImgsScroll.frame.size.height-height)/2.0;
    float gapX = 13;
    for (int i=0; i<[_photosList count]; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(origX+(gapX+width)*i, origY, width, height)];
        imageView.image =_photosList[i];
        imageView.layer.masksToBounds = YES;
        imageView.layer.cornerRadius = 3.0;
        // 事件监听
        imageView.tag = i;
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImage:)]];
        // 内容模式
        imageView.clipsToBounds = YES;
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        
        [_ImgsScroll addSubview:imageView];
        
    }
    if (_photosList.count >= 4) {
        [_cameraBtn setHidden:YES];
    }else{
        [_cameraBtn setHidden:NO];
    }
    [_cameraBtn setFrame:CGRectMake(origX+(gapX+width)*[_photosList count] +5, _cameraBtn.frame.origin.y, _cameraBtn.frame.size.width, _cameraBtn.frame.size.height)];
    _ImgsScroll.contentSize = CGSizeMake(_photosList.count >= 4 ? origX+(gapX+width)*[_photosList count]:origX+(gapX+width)*[_photosList count]+45, _ImgsScroll.frame.size.height);
}

- (void)tapImage:(UITapGestureRecognizer *)tap {
    NSArray *imgurlArray = _photosList;
    
    int count = _photosList.count;
    // 1.封装图片数据
    NSMutableArray *photos = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i<count; i++) {
        // 替换为中等尺寸图片
        //        NSString *url = imgurlArray[i];
        MJPhoto *photo = [[MJPhoto alloc] init];
        //        photo.placeholder = [_photosList objectAtIndex:i];
        //        photo.url = [NSURL URLWithString:url]; // 图片路径
        UIImageView *imageview = [[UIImageView alloc] initWithImage:[_photosList objectAtIndex:i]];
        //        [imageview sizeToFit];
        photo.srcImageView = imageview; // 来源于哪个UIImageView
        [photos addObject:photo];
    }
    
    // 2.显示相册
    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
    browser.currentPhotoIndex = (tap.view.tag>=100)?(tap.view.tag-100):tap.view.tag; // 弹出相册时显示的第一张图片是？
    browser.photos = photos; // 设置所有的图片
    [browser show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
